package cn.witque.controller;

import cn.witque.pojo.*;
import cn.witque.pojo.dto.Dto;
import cn.witque.pojo.vo.order.*;
import cn.witque.service.*;
import cn.witque.utils.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author jyk
 */
@Controller
@RequestMapping("/api/hotelorder")
public class ItripHotelOrderController {

    @Resource
    private ItripHotelOrderService itripHotelOrderService;

    @Resource
    private ItripHotelRoomService itripHotelRoomService;

    @Resource
    private ItripHotelTempStoreService itripHotelTempStoreService;

    @Resource
    private HotelService hotelService;

    @Resource
    private ItripOrderLinkUserService itripOrderLinkUserService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private RedisService redisService;



    /**
     * 查询订单列表
     *
     * @param orderListVo
     * @return
     */
    @ApiOperation(value = "查询订单列表", httpMethod = "POST")
    @RequestMapping(value = "/getpersonalorderlist", produces = "application/json", method = RequestMethod.POST)
    @ResponseBody
    public Dto queryOrderList(@RequestBody OrderListVo orderListVo, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (!redisService.isexist(token)) {
            return DtoUtil.getFailed("token失效了，请重新登录！", "139");
        }
        ItripUser user = redisService.getUserToken(token);

        try {

            ItripHotelOrder itripHotelOrder = new ItripHotelOrder();
            itripHotelOrder.setOrderType(orderListVo.getOrderType());
            itripHotelOrder.setOrderStatus(orderListVo.getOrderStatus());
            itripHotelOrder.setStartDate(orderListVo.getStartDate());
            itripHotelOrder.setLinkUserName(orderListVo.getLinkUserName());
            itripHotelOrder.setEndDate(orderListVo.getEndDate());
            itripHotelOrder.setOrderNo(orderListVo.getOrderNo());
            itripHotelOrder.setUserId(user.getId());
            //取总数量totalCount
            Integer totalCount = itripHotelOrderService.orderCount(itripHotelOrder);
            if (EmptyUtil.isEmpty(orderListVo.getPageNo())){
                orderListVo.setPageNo(1);
            }
            Page page=new Page(orderListVo.getPageNo(),orderListVo.getPageSize(),totalCount);
            itripHotelOrder.setPageIndex(page.getBeginPos());
            itripHotelOrder.setPageSize(page.getPageSize());
            List<ItripHotelOrder> list = itripHotelOrderService.queryOrderList(itripHotelOrder);
            page.setRows(list);

            return DtoUtil.getSuccess("获取个人订单列表成功!", page);

        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.getFailed("获取个人订单列表失败，请重试！","140");
        }


    }


    /**
     * 查询订单详细信息
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "查询订单详细信息",httpMethod = "GET")
    @RequestMapping(value = "/getpersonalorderinfo/{id}", produces = "application/json", method = RequestMethod.GET)
    @ResponseBody
    public Dto queryOrderDetails(@PathVariable Long id) {
       ItripHotelOrder order = itripHotelOrderService.queryOrderDetails(id);
        int i=order.getOrderStatus();
        if (i == 1) {
            order.setProcessNode("3");
        } else if (i == 0) {
            order.setProcessNode("2");//订单支付
        } else if (i == 2) {
            order.setProcessNode("3");//支付成功（未出行）
        } else if (i == 3) {
            order.setProcessNode("5");//订单点评
        } else if (i == 4) {
            order.setProcessNode("6");//订单完成
        } else {
            order.setProcessNode(null);
        }
        if (null==id){
            return DtoUtil.getFailed("查询参数订单ID为空!","1003");
        }
        if(null==order){
            return DtoUtil.getFailed("没有查询到订单!", "1004");
        }

        return DtoUtil.getSuccess("获取个人订单详细信息成功!",order);
    }





    /**
     * 查询个人订单详情有关的房屋信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "查询个人订单详情有关的房屋信息",httpMethod = "GET")
    @RequestMapping(value = "/getpersonalorderroominfo/{orderId}",produces = "application/json",method = RequestMethod.GET)
    @ResponseBody
    public Dto getPersonalOrderRoomInfoVo(@PathVariable String orderId) {

        GetPersonalOrderRoomInfoVo personalOrderRoomVO=itripHotelOrderService.getPersonalOrderRoomInfoVo(Long.valueOf(orderId));

        if (null==personalOrderRoomVO){
            return DtoUtil.getFailed("获取个人订单房屋信息失败!","1008");
        }
        return DtoUtil.getSuccess("获取个人订单房屋信息成功!",personalOrderRoomVO);
    }


    /**
     * 删除订单
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除订单",httpMethod = "POST")
    @RequestMapping(value = "/deleteByPrimaryKey", produces = "application/json", method = RequestMethod.POST)
    @ResponseBody
    public Dto deleteByPrimaryKey(@RequestParam Long id) {
        ItripHotelOrder itripHotelOrder = new ItripHotelOrder();
        itripHotelOrder.setId(id);

        int results=itripHotelOrderService.deleteByPrimaryKey(id);

        if (results>0){
            return DtoUtil.getSuccess("删除订单成功!", results);
        }
        return DtoUtil.getFailed("删除订单失败!", "1006");
    }


    @ApiOperation(value = "酒店预订",httpMethod = "POST")
    @RequestMapping(value = "/hotelBooking", produces = "application/json", method = RequestMethod.POST)
    @ResponseBody/*HttpServletRequest*/
    public Dto hotelBooking(@RequestBody HotelBookingVo hotelBookingVo ) throws ParseException {
        ItripHotelOrder itripHotelOrder = new ItripHotelOrder();

        itripHotelOrder.setCheckInDate(hotelBookingVo.getCheckInDate());
        itripHotelOrder.setBookingDays(hotelBookingVo.getBookingDays());
        itripHotelOrder.setLinkUserName(hotelBookingVo.getLinkUserName());
        itripHotelOrder.setNoticePhone(hotelBookingVo.getNoticePhone());
        itripHotelOrder.setIsNeedInvoice(hotelBookingVo.getIsNeedInvoice());
        itripHotelOrder.setInvoiceType(hotelBookingVo.getInvoiceType());
        itripHotelOrder.setInvoiceHead(hotelBookingVo.getInvoiceHead());
        itripHotelOrder.setSpecialRequirement(hotelBookingVo.getSpecialRequirement());

        //订单类型
        itripHotelOrder.setOrderType(1);
        //订单号
        itripHotelOrder.setOrderNo(OrderNoUtil.randomOrderNumber("queque"));
        //订单状态（0：待支付 1:已取消 2:支付成功 3:已消费 4：已点评）
        itripHotelOrder.setOrderStatus(0);
        //创建时间
        itripHotelOrder.setCreationDate(new Date());
        //用户id
        itripHotelOrder.setUserId(71L);
        //退房日期
        itripHotelOrder.setCheckOutDate(OrderNoUtil.checkOutDates(hotelBookingVo.getCheckInDate(),hotelBookingVo.getBookingDays()));
//        roomId
        //退房日期=入住日期+入住天数
        int results=itripHotelOrderService.insertSelective(itripHotelOrder);
        if (results>0){
            return DtoUtil.getSuccess("预订成功!", results);
        }
        return DtoUtil.getFailed("预订失败!", "1007");
    }

    @ApiOperation(value = "根据订单Id查对象",httpMethod = "GET")
    @RequestMapping(value = "/queryOrderById/{orderId}",method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto queryOrderById(@PathVariable Long orderId) {
        ItripHotelOrder order = itripHotelOrderService.queryOrderDetails(orderId);
        List<ItripOrderLinkUser> orderUser=itripOrderLinkUserService.selectByPrimaryKey(orderId);

        order.setItripOrderLinkUserList(orderUser);

        return DtoUtil.getSuccess("获取个人订单详细信息成功!",order);
    }



    @ApiOperation(value = "线下支付",httpMethod = "POST")
    @RequestMapping(value = "/updateorderstatusandpaytype",method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto updateorderstatusandpaytype(@RequestBody Map<String,Object> map ) {
        map.put("orderStatus", 2);
        int result = itripHotelOrderService.updateByPrimaryKeySelective(map);
        if (result < 0) {
            return DtoUtil.getFailed("支付失败！", "10010");
        }
        return DtoUtil.getSuccess("支付成功!");
    }


    @ApiOperation(value = "添加订单", httpMethod = "POST")
    @RequestMapping(value = "/addhotelorder", produces = "application/json", method = RequestMethod.POST)
    @ResponseBody
    public Dto addhotelorder(@RequestBody AddHotelOrderVO addHotelOrderVO, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (!redisService.isexist(token)) {
            return DtoUtil.getFailed("token失效了，请重新登录！", "139");
        }
        ItripUser itripUser = redisService.getUserToken(token);
        List<ItripUserLinkUser> linkUserList = addHotelOrderVO.getLinkUser();


        if (itripHotelTempStoreService.isHasStore(addHotelOrderVO)) {
            Integer days = DateUtil.getBetweenDates(addHotelOrderVO.getCheckInDate(), addHotelOrderVO.getCheckOutDate()).size() - 1;

            if (days <= 0) {
                return DtoUtil.getFailed("非法的退房时间！", "144");
            }

            ItripHotelOrder hotelOrder = new ItripHotelOrder();
            hotelOrder.setId(addHotelOrderVO.getId());
            hotelOrder.setUserId(itripUser.getId());
            hotelOrder.setOrderType(addHotelOrderVO.getOrderType());
            hotelOrder.setHotelId(addHotelOrderVO.getHotelId());
            hotelOrder.setHotelName(addHotelOrderVO.getHotelName());
            hotelOrder.setRoomId(addHotelOrderVO.getRoomId());
            hotelOrder.setCount(addHotelOrderVO.getCount());
            hotelOrder.setCheckInDate(addHotelOrderVO.getCheckInDate());
            hotelOrder.setCheckOutDate(addHotelOrderVO.getCheckOutDate());
            hotelOrder.setNoticePhone(addHotelOrderVO.getNoticePhone());
            hotelOrder.setNoticeEmail(addHotelOrderVO.getNoticeEmail());
            hotelOrder.setSpecialRequirement(addHotelOrderVO.getSpecialRequirement());
            hotelOrder.setIsNeedInvoice(addHotelOrderVO.getIsNeedInvoice());
            hotelOrder.setInvoiceHead(addHotelOrderVO.getInvoiceHead());
            hotelOrder.setInvoiceType(addHotelOrderVO.getInvoiceType());
            hotelOrder.setCreatedBy(itripUser.getId());
            hotelOrder.setBookingDays(days);


            StringBuilder lusb = new StringBuilder();
            for (int i = 0; i < linkUserList.size(); i++) {
                if (i < linkUserList.size() - 1) {
                    lusb.append(linkUserList.get(i).getLinkUserName() + ",");
                } else {
                    lusb.append(linkUserList.get(i).getLinkUserName());
                }
            }

            hotelOrder.setLinkUserName(lusb.toString());

            if (token.indexOf("Macintosh") != -1){
                hotelOrder.setBookType(0);
            }else if (token.indexOf("Windows") != -1){
                hotelOrder.setBookType(0);
            }else if (token.indexOf("iPhone") != -1){
                hotelOrder.setBookType(1);
            }else if (token.indexOf("Android") != -1){
                hotelOrder.setBookType(1);
            }else {
                hotelOrder.setBookType(2);
            }

            hotelOrder.setOrderStatus(0);
            hotelOrder.setOrderNo(OrderNoUtil.randomOrderNumber(itripUser.getUserCode()));
            ItripHotelRoom room = itripHotelRoomService.selectByPrimaryKey(addHotelOrderVO.getRoomId());
            BigDecimal oneNum = new BigDecimal(days*addHotelOrderVO.getCount());
            BigDecimal allMoney=oneNum.multiply(room.getRoomPrice().setScale(2,BigDecimal.ROUND_DOWN));
            hotelOrder.setPayAmount(allMoney);
            Map<String,String> map =  itripHotelOrderService.addItripOrder(hotelOrder,linkUserList);

            return DtoUtil.getSuccess("订单创建成功",map);
        }else {
            return DtoUtil.getFailed("库存不足，不能下单","145");
        }
    }


    /***
     * 10分钟执行一次 刷新订单的状态 不对外公布
     */
    @Scheduled(cron = "*0 0/10 * * * ?")
    public void flushCancelOrderStatus() {
        try {
            boolean flag = itripHotelOrderService.flushFail();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * 2小时执行一次 刷新订单的状态 不对外公布
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void flushOrderStatus() {
        try {
            boolean flag = itripHotelOrderService.flushSuccess();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "根据条件获得库存价格等信息", httpMethod = "POST")
    @RequestMapping(value = "/getpreorderinfo", produces = "application/json", method = RequestMethod.POST)
    @ResponseBody
    public Dto queryRoomInventory(@RequestBody ValiDateRoomStoreVO valiVO, HttpServletRequest request) {
        String token = request.getHeader("token");
        try {
            if (!redisService.isexist(token)) {
                return DtoUtil.getFailed("token失效了，请重新登录！", "139");
            }
            VerifyRoomInventoryVo verifyRoomInventoryVo = new VerifyRoomInventoryVo();
            ItripHotel itripHotel = hotelService.selectByPrimaryKey(valiVO.getHotelId());
            ItripHotelRoom room = itripHotelRoomService.selectByPrimaryKey(valiVO.getRoomId());
            List<StoreVo> storeVoList = itripHotelTempStoreService.queryRoomInventory(valiVO);
            verifyRoomInventoryVo.setCheckInDate(valiVO.getCheckInDate());
            verifyRoomInventoryVo.setCheckOutDate(valiVO.getCheckOutDate());
            verifyRoomInventoryVo.setHotelName(itripHotel.getHotelName());
            verifyRoomInventoryVo.setRoomId(room.getId());
            verifyRoomInventoryVo.setPrice(room.getRoomPrice());
            verifyRoomInventoryVo.setHotelId(valiVO.getHotelId());
            verifyRoomInventoryVo.setCount(1);
            if (storeVoList.size() < 1) {
                return DtoUtil.getFailed("暂时无房", "141");
            }
            verifyRoomInventoryVo.setStore(storeVoList.get(0).getStore());
            return DtoUtil.getSuccess("房间库存获取成功", verifyRoomInventoryVo);

        } catch (Exception e) {
            return DtoUtil.getFailed("程序出现异常！", "141");
        }
    }


}
